package org.imsetal.ilpointservice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.imsetal.ilapi.client.IlUserServiceClient;
import org.imsetal.ilapi.client.IlUserServiceClientByWebClient;
import org.imsetal.ilapi.utils.Result;
import org.imsetal.ilpointservice.mapper.UserpointMapper;
import org.imsetal.ilpointservice.pojo.Userpoint;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Service
public class UserPointService {
    @Resource
    UserpointMapper userpointMapper;
    @Resource
    IlUserServiceClient ilUserServiceClient;
    @Resource
    IlUserServiceClientByWebClient ilUserServiceClientByWebClient;

    public int selectUserPoint(Long userId) {
        Userpoint userpoint = userpointMapper.selectOne(new QueryWrapper<Userpoint>().eq("userid", userId));
        if (userpoint == null) {
            insertNewUserPointBook(userId);
            return 0;
        } else {
            return userpoint.getPoint();
        }
    }

    public void insertNewUserPointBook(Long userId) {

        Userpoint userpoint=new Userpoint(userId);
        userpoint.setPoint(0);
        userpointMapper.insert(userpoint);
    }

    public boolean addUserPoint(Long userId,int addPoint) {
        Userpoint userpoint=userpointMapper.selectOne(new QueryWrapper<Userpoint>().eq("userid",userId));
        if(userpoint==null){
            insertNewUserPointBook(userId);
            userpoint=userpointMapper.selectOne(new QueryWrapper<Userpoint>().eq("userid",userId));
        }
        userpoint.setPoint(userpoint.getPoint()+addPoint);
        userpointMapper.updateById(userpoint);
        return true;
    }

    public Mono<Boolean> tryToCheckUserExist(Long userId) {
        Mono<Result> res=ilUserServiceClientByWebClient.checkUserExist(userId);
        res.doOnNext(val->{
            System.out.println("获取到值:"+val.getData());
        }).subscribe();
        res.subscribe(val->{
            System.out.println("获取完成:"+val.getData());
        });
        return ilUserServiceClientByWebClient.checkUserExist(userId)
                .map(Result::getData)
                .map(data-> (Boolean) data);
    }
}
